package com.cby.android.base.capture

import android.content.Intent
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.ImageReader
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.cby.android.base.databinding.ActivityScreenCaptureBinding

const val REQUEST_MEDIA_PROJECTION = 1001
/**
 * @description: ScreenCaptureActivity
 * @author: ChenBaoYang
 * @createDate: 2022/7/21 10:08 上午
 */
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class ScreenCaptureActivity : AppCompatActivity() {

    private val binding by lazy { ActivityScreenCaptureBinding.inflate(layoutInflater) }
    private val mediaProjectionManager: MediaProjectionManager by lazy { getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager }
    private var mediaProjection: MediaProjection? = null
    private var virtualDisplay: VirtualDisplay? = null
    private val handler by lazy { Handler(Looper.getMainLooper()) }
    private val imageReader by lazy { ImageReader.newInstance(
        ScreenUtils.getScreenWidth(),
        ScreenUtils.getScreenHeight(), PixelFormat.RGBA_8888, 1) }


    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.btnStart.setOnClickListener {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(Intent(this, CaptureService::class.java))
            }
            // 延迟3秒，是为了推出桌面，截图应用外的图片
            handler.postDelayed({
                startScreenCapture()
            }, 3000)

        }
        binding.btnStop.setOnClickListener {
            Log.d("chenby", "Stop screen capture")
            stopScreenCapture()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_MEDIA_PROJECTION) {
            if (resultCode != RESULT_OK) {
                Log.d("chenby", "User cancelled")
                return
            }
            Log.d("chenby", "Starting screen capture")
            mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data!!)
            setUpVirtualDisplay()
        }
    }

    private fun startScreenCapture() {
        if (mediaProjection == null) {
            Log.d("chenby", "Requesting confirmation")
            // This initiates a prompt dialog for the user to confirm screen projection.
            startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION)
        } else {
            Log.d("chenby", "mediaProjection != null")
            setUpVirtualDisplay()
        }
    }

    private fun setUpVirtualDisplay() {
        Log.d("chenby", "setUpVirtualDisplay")
        virtualDisplay = mediaProjection!!.createVirtualDisplay(
            "ScreenCapture",
            ScreenUtils.getScreenWidth(),
            ScreenUtils.getScreenHeight(),
            ScreenUtils.getScreenDensityDpi(),
            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            imageReader.surface, null, null
        )
        handler.postDelayed({
            val image = imageReader.acquireLatestImage()
            if (image != null) {
                Log.d("chenby", "get image: ${image.planes.size}")
                binding.iv.setImageBitmap(ImageUtils.imageConvertToBitmap(image))
            } else {
                Log.d("chenby", "image == null")
            }
            stopScreenCapture()
        },1000)
    }

    private fun stopScreenCapture() {
        Log.d("chenby", "stopScreenCapture, virtualDisplay = $virtualDisplay")
        virtualDisplay?.release()
        virtualDisplay = null
    }
}